package com.api.shopapi.controller;

import com.alibaba.fastjson.JSONObject;

import com.api.shopapi.entity.*;
import com.api.shopapi.entity.dto.GovernmentDTO;
import com.api.shopapi.entity.dto.StaffDTO;
import com.api.shopapi.service.*;
import com.github.pagehelper.PageInfo;
//import javafx.concurrent.Worker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 政府
 * */
@RestController
@RequestMapping("Government")
public class GovernmentController extends BaseController {

    @Autowired
    @Qualifier("GovernmentServiceImplOne")
    private GovernmentService governmentService;

    @Autowired
    @Qualifier("StaffServiceImplOne")
    private StaffService staffService;

    @Autowired
    @Qualifier("RoleServiceImplOne")
    private RoleService roleService;

    @Autowired
    @Qualifier("ElderlyClassServiceImplOne")
    private ElderlyClassService elderlyClassService;


    @Autowired
    @Qualifier("UserServiceImplOne")
    private UserService userService;


    //获取信息
    @RequestMapping(value = "Get", method = RequestMethod.POST)
    public MyResult Get(@RequestBody JSONObject jsonObject) {

        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

//            if (!checkSignPC(timeStr, sign)) {
//                return failed("签名错误");
//            }
            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Government/Get");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            Staff staff = staffService.getByStaffCode(staffCode);

            Government government = governmentService.getByGovernmentCode(staff.getGovernmentCode());
            String topRoleCode = government.getTopRoleCode();

            GovernmentDTO governmentDTO = mapper.map(government, GovernmentDTO.class);
            if (topRoleCode == null) {
                governmentDTO.setRoleName(null);
            } else {
                Role role = roleService.getByRoleCode(topRoleCode);
                String roleName = role.getName();
                governmentDTO.setRoleName(roleName);
            }
            return success(governmentDTO);

        } catch (Exception e) {
            insertError("/Government/Get", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }

    }

    //列表
    @RequestMapping(value = "List", method = RequestMethod.POST)
    public MyResult List(@RequestBody JSONObject jsonObject) {

        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");

//            if (!checkSignPC(timeStr, sign)) {
//                return failed("签名错误");
//            }
            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Government/List");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            List<Government> listGovernment = governmentService.getList();

//            Government government = new Government();
//            government.setGovernmentCode(emptyUUID);
//            government.setName("全部政府");
//
//            listGovernment.add(government);

            List<Government> listGovernment2 = new ArrayList<>();
            for (int i = listGovernment.size() - 1; i >= 0; i--) {
                listGovernment2.add(listGovernment.get(i));
            }

            return success(listGovernment2);

        } catch (Exception e) {
            insertError("/Government/List", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }

    }

    //列表
    @RequestMapping(value = "ListForUser", method = RequestMethod.POST)
    public MyResult ListForUser(@RequestBody JSONObject jsonObject) {

        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");

//            if (!checkSignPC(timeStr, sign)) {
//                return failed("签名错误");
//            }
            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Government/ListForUser");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            List<Government> listGovernment = governmentService.getList();

            return success(listGovernment);

        } catch (Exception e) {
            insertError("/Government/ListForUser", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }

    }


    //列表
    @RequestMapping(value = "Page", method = RequestMethod.POST)
    public MyResult Page(@RequestBody JSONObject jsonObject) {

        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");

            int pageIndex = jsonObject.getInteger("pageIndex");
            int pageSize = jsonObject.getInteger("pageSize");

            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Government/Page");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            PageInfo<GovernmentDTO> pageInfoDTO = governmentService.getPageInfoDTO(pageIndex, pageSize);
            List<GovernmentDTO> listGovernmentDTO = pageInfoDTO.getList();
            for (GovernmentDTO governmentDTO : listGovernmentDTO) {

                //设置机构管理员,存在多个管理员的情况
                Staff staff1 = staffService.getByRoleNameGovernmentCode("政府管理员", governmentDTO.getGovernmentCode());
                if (staff1 != null) {
                    StaffDTO staffDTO1 = mapper.map(staff1, StaffDTO.class);
                    governmentDTO.setStaffDTO(staffDTO1);
                }

            }


            return success(pageInfoDTO);

        } catch (Exception e) {
            insertError("/Government/Page", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }

    }


    //添加
    @RequestMapping(value = "Add", method = RequestMethod.POST)
    @Transactional
    public MyResult Add(@RequestBody JSONObject jsonObject) {

        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            String name = jsonObject.getString("name");
            String tel = jsonObject.getString("tel");
            String contacts = jsonObject.getString("contacts");
            String address = jsonObject.getString("address");
            String topRoleCode = jsonObject.getString("topRoleCode");
            double lat = jsonObject.getDoubleValue("lat");
            double lon = jsonObject.getDoubleValue("lon");

            String phone = jsonObject.getString("phone");

            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Government/Add");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            //百度经纬度转成腾讯坐标经纬度
            double x_pi=3.14159265358979324;
            double x = lon - 0.0065, y = lat - 0.006;
            double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
            double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
            double tx_lon = z * Math.cos(theta);
            double tx_lat = z * Math.sin(theta);

            //根据经纬度反查地址
            String jsonStr = getAddressByLonLat(tx_lon + "", tx_lat + "");
            JSONObject jsonObject1 = JSONObject.parseObject(jsonStr);
            JSONObject result = jsonObject1.getJSONObject("result");
            JSONObject address_component = result.getJSONObject("address_component");
            String province = address_component.getString("province");
            String city = address_component.getString("city");
            String district = address_component.getString("district");
            JSONObject address_reference = result.getJSONObject("address_reference");
            String town = address_reference.getJSONObject("town").getString("title");
            String landmark = address_reference.getJSONObject("landmark_l2").getString("title");


            User user = userService.getByPhone(phone);
            if(user != null){
                return failed("手机号已注册");
            }

            user = new User();
            user.setUserCode(UUID.randomUUID().toString());
            user.setPhone(phone);
            user.setLoginName(phone);
            user.setPassword(getMD5Str(phone.substring(5,11)));
            user.setName(name);
            user.setCreateTime(new Date());
            user.setUserType(20);
            user.setStatus(1);
            user.setGovernmentCode(UUID.randomUUID().toString());
            userService.insert(user);


            Government government = new Government();
            government.setGovernmentCode(user.getGovernmentCode());
            government.setName(name);
            government.setTel(tel);
            government.setContacts(contacts);
            government.setAddress(address);
            government.setCreateTime(new Date());
            government.setTopRoleCode(topRoleCode);
            government.setProvince(province);
            government.setCity(city);
            government.setDistrict(district);
            government.setTown(town);
            government.setLandmark(landmark);
            government.setStatus(1);
            government.setUserCode(user.getUserCode());
            governmentService.insert(government);



            ElderlyClass elderlyClass=new ElderlyClass();
            elderlyClass.setElderlyClassCode(UUID.randomUUID().toString());
            elderlyClass.setName("默认");
            elderlyClass.setValue(1);
            elderlyClass.setSort(1);
            elderlyClass.setAddBalance(0);
            elderlyClass.setStaffCode(staffCode);
            elderlyClass.setGovernmentCode(government.getGovernmentCode());
            elderlyClassService.insert(elderlyClass);


            Object data = new Object[]{};
            return success(data);

        } catch (Exception e) {
            insertError("/Government/Add", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }

    }


    //编辑
    @RequestMapping(value = "Edit", method = RequestMethod.POST)
    public MyResult Edit(@RequestBody JSONObject jsonObject) {

        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");

            String name = jsonObject.getString("name");
            String tel = jsonObject.getString("tel");
            String contacts = jsonObject.getString("contacts");
            String address = jsonObject.getString("address");

            int status = jsonObject.getInteger("status");
            String governmentCode = jsonObject.getString("governmentCode");

            String topRoleCode = jsonObject.getString("topRoleCode");

            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Government/Edit");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }


            Government government = governmentService.getByGovernmentCode(governmentCode);
            if (government == null) {
                return failed("政府不存在");
            } else {
                government.setName(name);
                government.setTel(tel);
                government.setContacts(contacts);
                government.setAddress(address);
                government.setStatus(status);
                government.setTopRoleCode(topRoleCode);
                governmentService.updateByGovernmentCode(government);
            }


            Object data = new Object[]{};
            return success(data);

        } catch (Exception e) {
            insertError("/Government/Edit", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }

    }


    //编辑最后审核组织的等级
    @RequestMapping(value = "EditLastAuditZoneLevel", method = RequestMethod.POST)
    public MyResult EditLastAuditZoneLevel(@RequestBody JSONObject jsonObject) {

        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            int level = jsonObject.getInteger("level");
            String governmentCode = jsonObject.getString("governmentCode");

//            String topRoleCode = jsonObject.getString("topRoleCode");


//            if (!checkSignPC(timeStr, sign)) {
//                return failed("签名错误");
//            }
            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Government/EditLastAuditZoneLevel");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            Government government = governmentService.getByGovernmentCode(governmentCode);
            if (government == null) {
                return failed("机构不存在");
            } else {
                government.setElderlyLastAuditZoneLevel(level);
//                government.setTopRoleCode(topRoleCode);
                governmentService.updateByGovernmentCode(government);
            }


            Object data = new Object[]{};
            return success(data);

        } catch (Exception e) {
            insertError("/Government/EditLastAuditZoneLevel", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }

    }

    //设置政府角色
    @RequestMapping(value = "SetRole", method = RequestMethod.POST)
    public MyResult SetRole(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");
            String topRoleCode = jsonObject.getString("topRoleCode");
            PreCheck preCheck = checkSignAdmInterface(timeStr, sign,staffCode,"/Government/SetRole");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }
            Staff staff = staffService.getByStaffCode(staffCode);
            String governmentCode = staff.getGovernmentCode();

            Government government = governmentService.getByGovernmentCode(governmentCode);

            government.setTopRoleCode(topRoleCode);
            governmentService.updateByGovernmentCode(government);

            JSONObject jsonObject1 = new JSONObject();
            return success(jsonObject1);
        } catch (Exception e) {
//            e.printStackTrace();
            insertError("/Government/SetRole", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    //app注册获取政府信息
    @RequestMapping(value = "AppGetGovernment", method = RequestMethod.POST)
    public MyResult AppGetGovernment(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            double lon = jsonObject.getDoubleValue("lon");
            double lat = jsonObject.getDoubleValue("lat");
            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Government/AppGetGovernment");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            List<Government> governmentList = governmentService.getNormalGovernment();
            if (lon==0||lat==0){
                return success(governmentList);
            }


            /*//转成腾讯坐标经纬度
            double x_pi=3.14159265358979324;
            double x = lon - 0.0065, y = lat - 0.006;
            double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
            double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
            double tx_lon = z * Math.cos(theta);
            double tx_lat = z * Math.sin(theta);*/
            //根据经纬度反查地址
            String jsonStr = getAddressByLonLat(lon + "", lat + "");
            JSONObject jsonObject1 = JSONObject.parseObject(jsonStr);
            JSONObject result = jsonObject1.getJSONObject("result");
            JSONObject address_component = result.getJSONObject("address_component");
            String city = address_component.getString("city");
            String district = address_component.getString("district");
            JSONObject address_reference = result.getJSONObject("address_reference");
            String town = address_reference.getJSONObject("town").getString("title");



            List<Government> list=new ArrayList<>();
            List<Government> governmentCityList = governmentService.getByCity(city);
            List<Government> governmentDistrictList=new ArrayList<>();
            List<Government> governmentTownList=new ArrayList<>();
            if (governmentCityList.size()==1){

                Government government = governmentCityList.get(0);
                 list = getGovernmentList(government, governmentList);
            }else if (governmentCityList.size()==0){
                 list=governmentList;
            }else{
                for (Government government : governmentCityList) {
                    if (government.getDistrict().equals(district)){
                        governmentDistrictList.add(government);
                    }
                }
                if (governmentDistrictList.size()==1){
                    Government government = governmentDistrictList.get(0);
                    list=getGovernmentList(government,governmentList);
                }else if (governmentDistrictList.size()==0){
                    Government government = governmentCityList.get(0);
                    list=getGovernmentList(government,governmentList);
                }else {
                    for (Government government : governmentDistrictList) {
                        if (government.getTown().equals(town)){
                            governmentTownList.add(government);
                        }
                        if (governmentTownList.size()==1){
                            Government government1 = governmentTownList.get(0);
                            list=getGovernmentList(government1,governmentList);
                        }else if (governmentTownList.size()==0){
                            Government government1 = governmentDistrictList.get(0);
                            list=getGovernmentList(government1,governmentList);
                        }else {
                            Government government1 = governmentTownList.get(0);
                            list=getGovernmentList(government1,governmentList);
                        }
                    }
                }
            }

            return success(list);
        } catch (Exception e) {
//            e.printStackTrace();
            insertError("/Government/AppGetGovernment", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }



    private List<Government> getGovernmentList(Government government,List<Government> governmentList){
        List<Government> list=new ArrayList<>();
        list.add(government);
        for (Government government1 : governmentList) {
            if (!government1.getGovernmentCode().equals(government.getGovernmentCode())){
                list.add(government1);
            }
        }
        return list;
    }


    //查看所有政府
    @RequestMapping(value = "GetNormalGovernment", method = RequestMethod.POST)
    public MyResult GetNormalGovernment(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");
            PreCheck preCheck = checkSignAdmInterface(timeStr, sign,staffCode,"/Government/GetNormalGovernment");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }
            List<Government> governmentList = governmentService.getNormalGovernment();

            return success(governmentList);
        } catch (Exception e) {
//            e.printStackTrace();
            insertError("/Government/GetNormalGovernment", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }



}
